package sncf.client;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimerTask;

import sncf.server.SncfService;
import sncf.utils.AdminUtils;
import sncf.utils.Referential;

public class ConfirmTask extends TimerTask {

	@Override
	public void run() {
		SncfService service = SncfService.getInstance();
		Referential ref = Referential.getInstance();
		try {
			Date today = new Date();
			SimpleDateFormat dateFormatter = new SimpleDateFormat(
					"dd/MM/yyyy HH:mm");
			System.out.println("");
			System.out.println("");
			System.out
					.println("==== START CONFIRM TASK [CONFIRMED TRAIN LIST] at "
							+ dateFormatter.format(today) + " ====");

			boolean dayFilterEnabled = true;
			Collection<Train> trainSetToConfirm = ref
					.getTrainSetToConfirm(dayFilterEnabled);

			if (trainSetToConfirm != null && !trainSetToConfirm.isEmpty()) {
				List<Train> confirmedTrainList = service
						.getConfirmedTrainList(trainSetToConfirm);
				if (confirmedTrainList != null && !confirmedTrainList.isEmpty()) {
					for (Train train : confirmedTrainList) {
						System.out.println(train);
					}

					Set<Train> confirmedTrainSet = new HashSet<Train>();
					confirmedTrainSet.addAll(confirmedTrainList);

					if (ref.saveConfirm(confirmedTrainSet)) {
						ref.clearTrainSetToConfirm();

					}

				}
			} else {
				System.out.println("Aucun train en attente de confirmation");
			}
		} catch (Exception e) {
			e.printStackTrace();
			AdminUtils.notifySystemAdmin(e);
		} finally {
			ref.addTimeToNextConfirmDate(Calendar.DAY_OF_MONTH, 1);
			System.out
					.println("==== END CONFIRM TASK [CONFIRMED TRAIN LIST] ====");
			System.out.println("");
		}
	}

}
